package cn.zwz.bill.controller;

import cn.zwz.basics.baseVo.PageVo;
import cn.zwz.basics.baseVo.Result;
import cn.zwz.basics.utils.PageUtil;
import cn.zwz.basics.utils.ResultUtil;
import cn.zwz.basics.utils.SecurityUtil;
import cn.zwz.bill.entity.Bill;
import cn.zwz.bill.entity.Commodity;
import cn.zwz.bill.entity.Supplier;
import cn.zwz.bill.service.IBillService;
import cn.zwz.bill.service.ICommodityService;
import cn.zwz.bill.service.ISupplierService;
import cn.zwz.bill.utils.DateUtil;
import cn.zwz.bill.utils.DateUtils;
import cn.zwz.bill.vo.BillVo;
import cn.zwz.bill.vo.EChartsVo;
import cn.zwz.bill.vo.ProfitY;
import cn.zwz.bill.vo.Xaxis;
import cn.zwz.data.entity.User;
import cn.zwz.data.service.IUserService;
import cn.zwz.data.utils.ZwzNullUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 郑为中
 */
@RestController
@Api(tags = "账单管理")
@RequestMapping("/zwz/bill")
@Transactional
public class BillController {

    @Autowired
    private IBillService iBillService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private ICommodityService iCommodityService;

    @Autowired
    private ISupplierService iSupplierService;

    @Autowired
    private IUserService iUserService;

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ApiOperation(value = "查询单个账单")
    public Result<Bill> get(@RequestParam String id){
        Bill bill = iBillService.getById(id);
        return new ResultUtil<Bill>().setData(bill);
    }

    /**
     * 查询营收，根据当前库存量，判断库存属于哪一次入库，然后计算
     * @return
     */
    @RequestMapping(value = "/getCommodityHot", method = RequestMethod.GET)
    @ApiOperation(value = "查询热售商品")
    public Result<IPage<Commodity>> get(@ModelAttribute Commodity commodity, @ModelAttribute PageVo page){
        List<Bill> billList = iBillService.list(new QueryWrapper<Bill>().eq("state", "已出库"));
        List<Bill> revenueBillsList = new ArrayList<>();
        String billDateTime = page.getDateTime();
        String startTime;
        String endTime;
        try {
            String[] split = billDateTime.split(",");
            startTime = split[0];
            endTime = split[1];
        }catch (Exception e){
            startTime = "";
            endTime = "";
        }
        if (!startTime.equals("") || !endTime.equals("")){
            for (Bill b : billList) {
                if (DateUtil.after(b.getDateTime(),startTime) && DateUtil.before(b.getDateTime(),endTime)){
                    revenueBillsList.add(b);
                }
            }
        }else {
            revenueBillsList = billList;
        }
        // 收入 -成本 最大的即是热售。
        Map<String,Double> revenueBillAllMap = new HashMap();//收益统计
        List<String> revenueCommodityIdList = new ArrayList();//总收名单

        for (Bill b: revenueBillsList) {
            QueryWrapper<Bill> billQueryWrapper = new QueryWrapper<>();
            billQueryWrapper.eq("stock_id",b.getParentId());
            billQueryWrapper.eq("commodity_id",b.getCommodityId());
            billQueryWrapper.eq("state","已入库");
            Bill one = iBillService.getOne(billQueryWrapper);
            String price = one.getPrice();//进价
            String unitPrice = b.getPrice();//售价
            String number = b.getNumber();//数量
            double priceDouble = Double.parseDouble(price);
            double unitPriceDouble = Double.parseDouble(unitPrice);
            double numberDouble = Double.parseDouble(number);

            double profitNumber = numberDouble * (unitPriceDouble - priceDouble);
//            System.out.println("进价：" + priceDouble + ",售价：" + unitPriceDouble + ",数量：" + numberDouble + ",收益：" + profitNumber);

            Double sum = revenueBillAllMap.get(b.getCommodityId());
            if (sum != null){
                revenueBillAllMap.put(b.getCommodityId(),sum + (double)Math.round(profitNumber*100)/100);
            }else {
                revenueBillAllMap.put(b.getCommodityId(), (double)Math.round(profitNumber*100)/100);
                revenueCommodityIdList.add(b.getCommodityId());
            }
        }
//        System.out.println("1");
//        System.out.println(revenueCommodityIdList);
        BillVo billVo = new BillVo();
        for (String commodityId : revenueCommodityIdList) {
            Double aDouble = revenueBillAllMap.get(commodityId);
            Double revenue = billVo.getRevenue();
            if (revenue != null){
                if (revenue < aDouble){
                    billVo.setCommodityId(commodityId);
                    billVo.setRevenue(aDouble);
                }
            }else {
                billVo.setRevenue(aDouble);
                billVo.setCommodityId(commodityId);
            }
        }
//        System.out.println(billVo);
        QueryWrapper<Commodity> qw = new QueryWrapper<>();
        qw.eq("id",billVo.getCommodityId());
        IPage<Commodity> data = iCommodityService.page(PageUtil.initMpPage(page),qw);
        for (Commodity com : data.getRecords()) {
            Supplier supplier = iSupplierService.getById(com.getSupplierId());
            if(supplier != null) {
                com.setSupplierName(supplier.getName());
            }
        }
        return new ResultUtil<IPage<Commodity>>().setData(data);
    }

    @RequestMapping(value = "/getEChartsVo", method = RequestMethod.GET)
    @ApiOperation(value = "查询收益情况")
    public Result<EChartsVo> getAllProfit(@ModelAttribute Bill bill, @ModelAttribute PageVo page){
        List<Bill> billList = iBillService.list(new QueryWrapper<Bill>().eq("state", "已出库"));
        List<Bill> revenueBillsList = new ArrayList<>();
        String billDateTime = bill.getDateTime();
        String startTime;
        String endTime;
        try {
            String[] split = billDateTime.split(",");
            startTime = split[0];
            endTime = split[1];
        }catch (Exception e){
            startTime = "";
            endTime = "";
        }
        if (!startTime.equals("") || !endTime.equals("")){
            for (Bill b : billList) {
                if (DateUtil.after(b.getDateTime(),startTime) && DateUtil.before(b.getDateTime(),endTime)){
                    revenueBillsList.add(b);
                }
            }
        }else {
            revenueBillsList = billList;
        }
        // 收入 -成本 最大的即是热售。
        Map<String,Double> revenueBillAllMap = new HashMap();//收益统计
        List<String> revenueCommodityIdList = new ArrayList();//总收名单

        for (Bill b: revenueBillsList) {
            QueryWrapper<Bill> billQueryWrapper = new QueryWrapper<>();
            billQueryWrapper.eq("stock_id",b.getParentId());
            billQueryWrapper.eq("commodity_id",b.getCommodityId());
            billQueryWrapper.eq("state","已入库");
            Bill one = iBillService.getOne(billQueryWrapper);
            String price = one.getPrice();//进价
            String unitPrice = b.getPrice();//售价
            String number = b.getNumber();//数量
            double priceDouble = Double.parseDouble(price);
            double unitPriceDouble = Double.parseDouble(unitPrice);
            double numberDouble = Double.parseDouble(number);

            double profitNumber = numberDouble * (unitPriceDouble - priceDouble);
//            System.out.println("进价：" + priceDouble + ",售价：" + unitPriceDouble + ",数量：" + numberDouble + ",收益：" + profitNumber);

            Double sum = revenueBillAllMap.get(b.getCommodityId());
            if (sum != null){
                revenueBillAllMap.put(b.getCommodityId(),sum + (double)Math.round(profitNumber*100)/100);
            }else {
                revenueBillAllMap.put(b.getCommodityId(), (double)Math.round(profitNumber*100)/100);
                revenueCommodityIdList.add(b.getCommodityId());
            }
        }
//        System.out.println("1");
//        System.out.println(revenueCommodityIdList);
        List<String> nameBar = new ArrayList<>();
        List<ProfitY> series = new ArrayList<>();
        List<Double> profitY = new ArrayList<>();
        for (String commodityId : revenueCommodityIdList) {
            Double aDouble = revenueBillAllMap.get(commodityId);
            Commodity iCommodityServiceById = iCommodityService.getById(commodityId);
            nameBar.add(iCommodityServiceById.getName());
            profitY.add((double)Math.round(aDouble*100)/100);
        }
        EChartsVo eChartsVo = new EChartsVo();

        Map<String,List<String>> categories = new HashMap<>();
        categories.put("categories",nameBar);
        Map<String,Map<String,List<String>>> xaxis = new HashMap<>();
        xaxis.put("xaxis",categories);
        eChartsVo.setXaxis(xaxis);

        ProfitY py = new ProfitY();
        py.setName("收益(元)");
        py.setData(profitY);
        series.add(py);
        eChartsVo.setSeries(series);
        return new ResultUtil<EChartsVo>().setData(eChartsVo);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "查询全部账单")
    public Result<List<Bill>> getAll(){
        List<Bill> list = iBillService.list();
        return new ResultUtil<List<Bill>>().setData(list);
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ApiOperation(value = "查询账单")
    public Result<IPage<Bill>> getByPage(@ModelAttribute Bill bill, @ModelAttribute PageVo page){
        QueryWrapper<Bill> qw = new QueryWrapper<>();
        if(!ZwzNullUtils.isNull(bill.getUserId())) {
            qw.eq("user_id",bill.getUserId());
        }
        if(!ZwzNullUtils.isNull(bill.getCommodityId())) {
            qw.eq("commodity_id",bill.getCommodityId());
        }
        if(!ZwzNullUtils.isNull(bill.getSupplierId())) {
            qw.eq("supplier_id",bill.getSupplierId());
        }
        IPage<Bill> data = iBillService.page(PageUtil.initMpPage(page),qw);
        List<Bill> overBillList = new ArrayList<>();
        String billDateTime = bill.getDateTime();
        String startTime;
        String endTime;
        try {
            String[] split = billDateTime.split(",");
            startTime = split[0];
            endTime = split[1];
        }catch (Exception e){
            startTime = "";
            endTime = "";
        }
        if (!startTime.equals("") || !endTime.equals("")){
            List<Bill> list = iBillService.list(qw);
            for (Bill b : list) {
                if (DateUtil.after(b.getDateTime(),startTime) && DateUtil.before(b.getDateTime(),endTime)){
                    overBillList.add(b);
                }
            }
            data.setRecords(overBillList);
            data.setTotal(overBillList.size());
            data.setPages(1);
            data.setCurrent(1);
            data.setSize(overBillList.size());
        }
        for (Bill bill1 : data.getRecords()) {
            Supplier supplier = iSupplierService.getById(bill1.getSupplierId());
            if(supplier != null) {
                bill1.setSupplierName(supplier.getName());
            } else {
                bill1.setSupplierName("无");
            }
            Commodity commodity = iCommodityService.getById(bill1.getCommodityId());
            if(commodity != null) {
                bill1.setCommodityName(commodity.getName());
            } else {
                bill1.setCommodityName("无");
            }
            User user = iUserService.getById(bill1.getUserId());
            if(user != null) {
                bill1.setUserName(user.getNickname());
            } else {
                bill1.setUserName("无");
            }
        }
        return new ResultUtil<IPage<Bill>>().setData(data);
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ApiOperation(value = "新增账单")
    public Result<Bill> insert(Bill bill) {
        bill.setDateTime(DateUtils.getCompleteNowDate());
        bill.setUserId(securityUtil.getCurrUser().getId());
        String price = bill.getPrice();
        String number = bill.getNumber();
        Double sum = Double.parseDouble(price) * Double.parseDouble(number);
        sum = Math.ceil(sum * 10.0) / 10.0;
        bill.setSum(sum + "");
        if(iBillService.saveOrUpdate(bill)){
            return new ResultUtil<Bill>().setData(bill);
        }
        return new ResultUtil<Bill>().setErrorMsg("新增账单失败");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation(value = "编辑账单")
    public Result<Bill> update(Bill bill) {
        if(iBillService.saveOrUpdate(bill)){
            return new ResultUtil<Bill>().setData(bill);
        }
        return new ResultUtil<Bill>().setErrorMsg("编辑账单失败");
    }
    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @ApiOperation(value = "删除账单")
    public Result<Object> delAllByIds(@RequestParam String[] ids) {
        for(String id : ids){
            iBillService.removeById(id);
        }
        return ResultUtil.success();
    }

}
